import FormCustomQueryApi from "@/api/form/core/formCustomQuery";

import {I18Parse,CommonLang} from '@lowcode/jpaas-common-lib';
import formComponentLang from '../../../../../locales/lang/impl/form/formComponentLang';
let lang = formComponentLang;
let i18n=function (langKey,text) {
    return I18Parse.getI18Val(lang.formComponent,langKey, text)
}


const ComponentDef = {

    props: {
        layout: '',
        conf: '',
        type: '',
        index: '',
        item: '',
        portalLayout:false,
        paramConfig:"",
        mdl:''
    },
    data(){
      return {
          constantField: [],
          params:[]
      }
    },
    created() {
        if(this.portalLayout && this.sourceAry){
            this.sourceAry=[{ value: 'event', label: i18n('form.event','来自事件') }]
        }
        if(this.paramConfig){
            this.params=JSON.parse(this.paramConfig)
        }
        this.loadConstants();
    },
    methods: {
        customViewI18n(name, text, key) {
            return this.$ti18(name, text, "customViewLang", key);
        },
        getAllLayout(){
            var layout = [];
            if (this.type == 'drag') {
                var layTmp = [];
                for (var i = 0; i < this.layout.length; i++) {
                    var cfg = this.layout[i].config;
                    if (this.layout[i].defConf == 'tab') {
                        layout.push(...cfg);
                    } else {
                        layout.push(this.layout[i]);
                    }
                }
            } else {
                for (var key in this.layout.layoutModel) {
                    if (this.layout.layoutModel[key]) {
                        if (this.layout[key].showTab == 'yes') {
                            layout.push(...this.layout[key].tabData);
                        } else {
                            layout.push(this.layout[key].selectModel);
                        }
                    }
                }
            }
            return layout;
        },
        isAliasExist(key) {
            var layout=this.getAllLayout();
            var aryTmp = layout.filter(item => {
                var cfg = item.config;
                return (cfg.alias == key && cfg.component == this.config.component && !cfg.pmtAlias);
            });
            if (aryTmp.length > 0 && this.config.alias != key) {
                this.$notification.warning({message:this.$ti18('rxMsa.tipsInfo', '提示信息'), description: i18n('tip.layout','组件在布局中已存在,请重新选择!')});
                return true;
            }
            return false;
        },
        isPmtAliasExist(key,pmtAlias){
            var layout=this.getAllLayout();
            var aryTmp = layout.filter(item => {
                var cfg = item.config;
                return (cfg.alias == key && cfg.component == this.config.component && cfg.pmtAlias==pmtAlias);
            });
            if (aryTmp.length > 1) {
                this.$notification.warning({message:this.$ti18('rxMsa.tipsInfo', '提示信息'), description: i18n('tip.selected','组件在布局中已选择此数据权限,请重新选择!')});
                return true;
            }
            return false;
        },
        getPublishComponents() {
            var layout = [];
            let types=['drag','chart' ,'ureport' ,'calendar',"filter","custom" ,"gisMap" ]
            if (types.includes(this.type) ) {
                for (var i = 0; i < this.layout.length; i++) {
                    var cfg = this.layout[i].config;
                    if (this.layout[i].defConf == 'tab') {
                        layout.push(...cfg);
                    } else {
                        layout.push(this.layout[i]);
                    }
                }
            } else {
                for (var key in this.layout.layoutModel) {
                    if (this.layout.layoutModel[key]) {
                        if (this.layout[key].showTab == 'yes') {
                            layout.push(...this.layout[key].tabData);
                        } else {
                            layout.push(this.layout[key].selectModel);
                        }
                    }
                }
            }
            //将表单组件放入
            for (var i = 0; i < this.layout.length; i++) {
                var conf = this.layout[i].config;
                if (conf.component =="form-component") {
                    var obj= layout.find((item) => item.id === this.layout[i].id);
                    if(!obj){
                        layout.push(this.layout[i]);
                    }
                }
            }
            var ary = layout.filter(item => {
                var pubSetting = item.config.publish;
                var component=item.config.component;
                //允许数据来自表单。
                if(component=="form-component"){
                    return true;
                }
                if (pubSetting && pubSetting.paramMapping && pubSetting.paramMapping.length > 0) {
                    return true;
                }

                return false;
            });
            return ary;
        },
        getPublishOptions() {
            var ary = this.getPublishComponents();
            var rtn = [];
            for (var i = 0; i < ary.length; i++) {
                var config = ary[i].config;
                var obj = {value: config.alias, label: config.name};
                rtn.push(obj);
            }
            return rtn;
        },
        getPubParams(key) {
            let components = this.getPublishComponents();
            let component = {};
            let found = false;
            for (var i = 0; i < components.length; i++) {
                component = components[i];
                if (component.config.alias == key) {
                    found = true;
                    break;
                }
            }
            let ary = [];
            if (!found) {
                return ary;
            }

            let params = component.config.publish && component.config.publish.paramMapping ?component.config.publish.paramMapping:[];
            for (let i = 0; i < params.length; i++) {
                let obj = params[i];
                let o = {value: obj.key, label: obj.label};
                ary.push(o);
            }
            return ary;
        },
        loadConstants() {
            FormCustomQueryApi.getConstants().then((data) => {
                this.constantField = this.constantField.concat(
                    data.map((item) => {
                        return { label: item.val, value: item.key }
                    })
                )
            })
        },
        //生成代码
        genCode(){
            //获取组件
            let component= this.config.receive.publishComponent;
            if(!component){
                this.$message.warning(i18n('tip.empty','发布事件组件不能为空!'));
                return;
            }
            let params={};
            //构造参数
            let mapping= this.config.receive.mapping;
            let ary=mapping.filter(item=>{
                return item.valueSource == 'param';
            });
            for(let item of ary){
                params[item.name]="";
            }
            let paramsStr=JSON.stringify(params);
            let event=`var event = {component: '${component}', params: ${paramsStr}};
            this.$bus.emit('formEvent', event);`
            this.copyText(event);
            this.$message.info(i18n('tip.successful',"生成发布事件成功,代码在剪切板中，你可以粘贴进行使用!"));
        },
        copyText(text){
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(text);
            }else {
                let textArea=document.querySelector("#temp_textarea");
                if(!textArea){
                    textArea = document.createElement('textarea');
                    textArea.setAttribute("id","temp_textarea");
                    // 使text area不在viewport，同时设置不可见
                    document.body.appendChild(textArea)
                }
                textArea.value = text;
                textArea.focus()
                textArea.select()
                // 执行复制命令并移除文本框
                document.execCommand('copy');
                textArea.remove();
            }
        }
    }

}

export default ComponentDef;